package com.example.exam.service.impl;

import com.example.exam.entity.User;
import com.example.exam.repository.UserRepository;
import com.example.exam.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


/**
 * @author shishuqian
 * date 2021/5/12
 * time 15:38
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public User findById(Integer id) {
        Optional<User> user = userRepository.findById(id);
        return user.orElse(null);
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    //token 12小时后失效
    //public final static int EXPIRE = 12;

    /*@Override
    public String createToken(User user) {
        //用UUID生成token
        String token = UUID.randomUUID().toString().replace("-","").toLowerCase();
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        //过期时间
        LocalDateTime expireTime = now.plusHours(EXPIRE);
        //保存到数据库
        user.setLoginTime(now);
        user.setExpireTime(expireTime);
        user.setToken(token);
        userRepository.save(user);
        return token;
    }

    @Override
    public void logout(String token) {
        User user = userRepository.findByToken(token);
        String token1 = UUID.randomUUID().toString().replace("-","").toLowerCase();
        //修改用户token使原本token失效，前端需配合将token清楚
        user.setToken(token1);
        userRepository.save(user);
    }

    @Override
    public User findByToken(String token) {
        return userRepository.findByToken(token);
    }*/
}
